/*
 * @lc app=leetcode.cn id=819 lang=typescript
 *
 * [819] 最常见的单词
 */

// @lc code=start
function mostCommonWord(paragraph: string, banned: string[]): string {
  const isBanned = new Set(banned);
  const map = new Map<string, number>();

  const isLetter = (c: string) => {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  };

  // 增加哨兵，方便处理
  paragraph += '!';
  const n = paragraph.length;

  let sb = '';
  for (let i = 0; i < n; i++) {
    // 如果是字母，则添加到sb中
    if (isLetter(paragraph[i])) {
      sb += paragraph[i].toLowerCase();
    } else {
      // 如果不是字母，开始处理sb
      if (sb.length > 0) {
        if (!isBanned.has(sb)) {
          map.set(sb, map.has(sb) ? map.get(sb)! + 1 : 1);
        }
        sb = '';
      }
    }
  }

  let ans = '';
  let max = 0;
  // 遍历map，找到出现频率最高的单词
  for (const [word, freq] of map) {
    if (freq > max) {
      max = freq;
      ans = word;
    }
  }

  return ans;
}
// @lc code=end
